package gen.desktop.sqlite;

import gen.core.exceptions.GenException;
import gen.core.utils.GenUtils;
import gen.desktop.Application;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.util.Properties;

import org.apache.commons.dbutils.QueryRunner;

public class Client {
	public Connection createConnection(){
		return createConnection(Application.getRepository());
	}
	
	public Connection createConnection(String theDatabaseFile) {
		boolean isDatabaseFileExist;
		try {
			isDatabaseFileExist = new File(theDatabaseFile).createNewFile();
		} catch (IOException ex) {
			throw new GenException(ex, "尝试创建数据文件时，发生异常！");
		}

		Properties aProperties = new Properties();
		aProperties.setProperty("driver", "org.sqlite.JDBC");
		aProperties.setProperty("url", "jdbc:sqlite:" + theDatabaseFile);

		Connection conn = GenUtils.createConnection(aProperties);
		if (isDatabaseFileExist) {
			try {
				initDatabase(conn);
				conn.commit();
			} catch (Exception ex) {
				GenUtils.closeConnection(conn);
				throw new GenException(ex, "提交建表语句时，发生异常！");
			}
		}

		return conn;
	}

	private void initDatabase(Connection conn) {
		String sql;
		QueryRunner runner = new QueryRunner();

		try {
			sql = "CREATE TABLE GEN_TEMPLATE(ID TEXT, NAME TEXT, DESCRIPTION TEXT, CATAGORY TEXT, CONTENT TEXT, OWNER TEXT, CREATE_TIME TEXT, MODIFIED_TIME TEXT)";
			runner.update(conn, sql);
			
			sql = "CREATE TABLE GEN_CONN_CONFIG(ID TEXT, NAME TEXT, DESCRIPTION TEXT, CATAGORY TEXT, DRIVER TEXT, URL TEXT, USER TEXT, PASSWORD TEXT, OWNER TEXT, CREATE_TIME TEXT, MODIFIED_TIME TEXT)";
			runner.update(conn, sql);

			sql = "CREATE TABLE GEN_SQL(ID TEXT, NAME TEXT, TEMPLATE_ID TEXT, DESCRIPTION TEXT, CATAGORY TEXT, CONTENT TEXT, OWNER TEXT, CREATE_TIME TEXT, MODIFIED_TIME TEXT)";
			runner.update(conn, sql);
		} catch (Exception ex) {
			throw new GenException(ex, "初始化数据库时，发生异常！");
		}
	}
}
